using Blazored.LocalStorage;
using ChuTiJingTai.Models;
using System.Text.Json;

namespace ChuTiJingTai.Services
{
    /// <summary>
    /// 本地存储服务实现
    /// </summary>
    public class LocalStorageService : ILocalStorageService
    {
        private readonly Blazored.LocalStorage.ILocalStorageService _blazoredLocalStorage;
        private readonly ILogger<LocalStorageService> _logger;

        // 存储键名常量
        private const string CHILDREN_KEY = "children";
        private const string API_CONFIG_KEY = "api_config";
        private const string EXAM_PAPERS_KEY = "exam_papers";
        private const string LOGS_KEY = "logs";

        public LocalStorageService(Blazored.LocalStorage.ILocalStorageService blazoredLocalStorage, ILogger<LocalStorageService> logger)
        {
            _blazoredLocalStorage = blazoredLocalStorage;
            _logger = logger;
        }

        #region 孩子档案管理

        public async Task<List<ChildProfile>> GetChildrenAsync()
        {
            try
            {
                var children = await GetItemAsync<List<ChildProfile>>(CHILDREN_KEY);
                return children ?? new List<ChildProfile>();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取孩子列表时发生错误");
                return new List<ChildProfile>();
            }
        }

        public async Task<ChildProfile?> GetChildAsync(int id)
        {
            var children = await GetChildrenAsync();
            return children.FirstOrDefault(c => c.Id == id);
        }

        public async Task<int> SaveChildAsync(ChildProfile child)
        {
            try
            {
                var children = await GetChildrenAsync();
                
                if (child.Id == 0)
                {
                    // 新增
                    child.Id = children.Any() ? children.Max(c => c.Id) + 1 : 1;
                    children.Add(child);
                }
                else
                {
                    // 更新
                    var existingIndex = children.FindIndex(c => c.Id == child.Id);
                    if (existingIndex >= 0)
                    {
                        children[existingIndex] = child;
                    }
                    else
                    {
                        children.Add(child);
                    }
                }

                await SetItemAsync(CHILDREN_KEY, children);
                return child.Id;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "保存孩子档案时发生错误");
                throw;
            }
        }

        public async Task<bool> DeleteChildAsync(int id)
        {
            try
            {
                var children = await GetChildrenAsync();
                var removed = children.RemoveAll(c => c.Id == id) > 0;
                if (removed)
                {
                    await SetItemAsync(CHILDREN_KEY, children);
                }
                return removed;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "删除孩子档案时发生错误");
                return false;
            }
        }

        #endregion

        #region API配置管理

        public async Task<ApiConfig?> GetApiConfigAsync()
        {
            try
            {
                return await GetItemAsync<ApiConfig>(API_CONFIG_KEY);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取API配置时发生错误");
                return null;
            }
        }

        public async Task SaveApiConfigAsync(ApiConfig config)
        {
            try
            {
                await SetItemAsync(API_CONFIG_KEY, config);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "保存API配置时发生错误");
                throw;
            }
        }

        #endregion

        #region 试卷管理

        public async Task<List<ExamPaper>> GetExamPapersAsync()
        {
            try
            {
                var papers = await GetItemAsync<List<ExamPaper>>(EXAM_PAPERS_KEY);
                return papers ?? new List<ExamPaper>();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取试卷列表时发生错误");
                return new List<ExamPaper>();
            }
        }

        public async Task<List<ExamPaper>> GetExamPapersByChildAsync(int childId)
        {
            var papers = await GetExamPapersAsync();
            return papers.Where(p => p.ChildId == childId).ToList();
        }

        public async Task<ExamPaper?> GetExamPaperAsync(int id)
        {
            var papers = await GetExamPapersAsync();
            return papers.FirstOrDefault(p => p.Id == id);
        }

        public async Task<int> SaveExamPaperAsync(ExamPaper paper)
        {
            try
            {
                var papers = await GetExamPapersAsync();
                
                if (paper.Id == 0)
                {
                    // 新增
                    paper.Id = papers.Any() ? papers.Max(p => p.Id) + 1 : 1;
                    papers.Add(paper);
                }
                else
                {
                    // 更新
                    var existingIndex = papers.FindIndex(p => p.Id == paper.Id);
                    if (existingIndex >= 0)
                    {
                        papers[existingIndex] = paper;
                    }
                    else
                    {
                        papers.Add(paper);
                    }
                }

                await SetItemAsync(EXAM_PAPERS_KEY, papers);
                return paper.Id;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "保存试卷时发生错误");
                throw;
            }
        }

        public async Task<bool> DeleteExamPaperAsync(int id)
        {
            try
            {
                var papers = await GetExamPapersAsync();
                var removed = papers.RemoveAll(p => p.Id == id) > 0;
                if (removed)
                {
                    await SetItemAsync(EXAM_PAPERS_KEY, papers);
                }
                return removed;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "删除试卷时发生错误");
                return false;
            }
        }

        #endregion

        #region 日志管理

        public async Task<List<LogEntry>> GetLogsAsync()
        {
            try
            {
                var logs = await GetItemAsync<List<LogEntry>>(LOGS_KEY);
                return logs ?? new List<LogEntry>();
            }
            catch (Exception ex)
            {
                Console.WriteLine($"获取日志时发生错误: {ex.Message}");
                return new List<LogEntry>();
            }
        }

        public async Task<List<LogEntry>> GetLogsByLevelAsync(string level)
        {
            var logs = await GetLogsAsync();
            return logs.Where(l => l.Level == level).ToList();
        }

        public async Task AddLogAsync(LogEntry log)
        {
            try
            {
                var logs = await GetLogsAsync();
                
                if (log.Id == 0)
                {
                    log.Id = logs.Any() ? logs.Max(l => l.Id) + 1 : 1;
                }
                
                logs.Add(log);

                // 保持最近1000条日志
                if (logs.Count > 1000)
                {
                    logs = logs.OrderByDescending(l => l.Timestamp).Take(1000).ToList();
                }

                await SetItemAsync(LOGS_KEY, logs);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"添加日志时发生错误: {ex.Message}");
            }
        }

        public async Task ClearLogsAsync()
        {
            try
            {
                await RemoveItemAsync(LOGS_KEY);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "清空日志时发生错误");
                throw;
            }
        }

        #endregion

        #region 通用方法

        public async Task<T?> GetItemAsync<T>(string key)
        {
            return await _blazoredLocalStorage.GetItemAsync<T>(key);
        }

        public async Task SetItemAsync<T>(string key, T value)
        {
            await _blazoredLocalStorage.SetItemAsync(key, value);
        }

        public async Task RemoveItemAsync(string key)
        {
            await _blazoredLocalStorage.RemoveItemAsync(key);
        }

        public async Task ClearAllAsync()
        {
            await _blazoredLocalStorage.ClearAsync();
        }

        #endregion
    }
} 